package com.stockz.equity.charting.painter.indicator;

import java.awt.Graphics2D;
import java.awt.Rectangle;

import org.springframework.stereotype.Component;

import com.stockz.equity.charting.display.indicator.AbstractDisplayableIndicatorConfiguration;
import com.stockz.equity.charting.util.ContextUtil;
import com.stockz.equity.charting.util.MathUtil;
import com.stockz.equity.charting.view.StockChartPanelState;
import com.stockz.equity.charting.view.StockChartView;
import com.stockz.equity.charting.view.StockRectangle;
import com.stockz.equity.pattern.Painter;

@Component
public class BarIndicatorPainter implements Painter<AbstractDisplayableIndicatorConfiguration> {

	@Override
	public void paint(Graphics2D g, AbstractDisplayableIndicatorConfiguration indicatorDisplay, Rectangle r) {
		
		StockRectangle rectangle = indicatorDisplay.getRectangle();
		if (rectangle != null && !rectangle.isEmpty()) {
			g.setClip(rectangle);
			
			double[] values = indicatorDisplay.getValues();
			StockChartView stockChartView = (StockChartView)ContextUtil.getApplicationContext().getBean(StockChartView.class);
			StockChartPanelState state = stockChartView.getSelectedStockChart()
					.getStockChartPanel().getStockChartPanelState();
			for (int i = state.getEndIndex() - 1; i >= state.getStartIndex(); i--) {
				if (i >= values.length || i <= 0) {
					continue;
				}
				
				int x = MathUtil.fitX(
						rectangle.x, 
						state.getTimeUnitSpace(),
						state.getEndIndex(), 
						i)-state.getTimeUnitSpace()/2;
				int y = MathUtil.fitY(
						rectangle.y,
						rectangle.y + rectangle.height,
						rectangle.getMinimumValueVisible(),
						rectangle.getMaximumValueVisible(), values[i],
						state.isSemiLog());
				g.setColor(indicatorDisplay.getColor());
				g.fillRect(x, y, state.getTimeUnitSpace(), rectangle.y + rectangle.height - y);
				g.setColor(stockChartView.getSelectedStockChart()
						.getStockChartPanel().getStockChartPanelSkin().getBackgroundColor());
				g.drawLine(x, y, x, rectangle.y + rectangle.height);
			}
			g.setClip(null);
		}
		
	}

}
